#
# ps9pr4.py  (Problem Set 9, Problem 4)
#
# AI Player for use in Connect Four
#
import random
from ps9pr2 import Player
from ps9pr1 import Board
class AIPlayer(Player):
    def __init__(self, checker, tiebreak, lookahead):
        """ put your docstring here
        """
        assert (checker == 'X' or checker == 'O')
        assert (tiebreak == 'LEFT' or tiebreak == 'RIGHT' or tiebreak == 'RANDOM')
        assert (lookahead >= 0)
        super(AIPlayer,self).__init__(checker)
        self.tiebreak = tiebreak
        self.lookahead = lookahead

    def __repr__(self):
        return 'Player %s (%s,%d)'%(self.checker,self.tiebreak,self.lookahead)

    def max_score_column(self,scores):
        max_score = max(scores)
        max_index = [index for index, value in enumerate(scores) if value == max_score]
        if self.tiebreak == 'LEFT':
            return max_index[0]
        elif self.tiebreak =='RIGHT':
            return  max_index[-1]
        else:
            return max_index[random.randint(0,len(max_index)-1)]

    def scores_for(self,board):
        scores =[]
        for col in range(board._width):
            cur_score = -1
            if board._slots[0][col] != ' ':
                cur_score = -1
            elif board.is_win_for(self.checker):
                cur_score = 100
            elif board.is_win_for(self.opponent_checker()):
                cur_score = 0
            elif self.lookahead == 0:
                cur_score = 50
            else:
                board.add_checker(self.checker,col)
                oppo_aiplayer = AIPlayer(self.opponent_checker(),self.tiebreak,self.lookahead-1)
                oppo_scores = oppo_aiplayer.scores_for(board)
                #if self.lookahead%2 == 0:
                #    cur_score = min(oppo_scores)
                    #cur_score = max([100-score if score>=0 else score for score in oppo_scores])
                #if self.lookahead%2 == 1:
                cur_score = 100 -max(oppo_scores)   #a loss for my opponent is a win for me
                board.remove_checker(col)
            scores.append(cur_score)
        #print(scores)
        return scores

    def next_move(self,board):
        self.num_moves +=1
        col_num = self.max_score_column(self.scores_for(board))
        return col_num

if __name__=='__main__':
    b = Board(6, 7)
    b.add_checkers('1211244445')
    s = AIPlayer('X', 'RANDOM', 2).next_move(b)#[0, 0, 0, 50, 0, 0, 0]
    print(s)